class myPromise {
    static PENDING = 'pending'
    static FULFILLED = 'fulfilled'
    static REJECTED = 'rejected'
    constructor(executor) {
        this.status = myPromise.PENDING
        this.value = null
        this.callback = []
        //使用try  是因为 外面使用不调用resolve  reject以外其他的 将会报错
        try {
            executor(this.resolve.bind(this), this.reject.bind(this))
        } catch (error) {
            this.reject(error)
        }
    }
    resolve(value) {
        if (this.status === myPromise.PENDING) {
            this.status = myPromise.FULFILLED
            this.value = value
            setTimeout(() => {// then的值需要在reject或resolve之后执行
                this.callback.map(item => {
                    item.onFulfilled(value)
                })
            })
        }
    }
    reject(reason) {
        if (this.status === myPromise.PENDING) {
            this.status = myPromise.REJECTED
            this.value = reason
            setTimeout(() => {
                this.callback.map(item => {
                    item.onRejected(reason)
                })
            })
        }
    }
    then(onFulfilled, onRejected) {
        if (typeof onFulfilled !== 'function') {
            onFulfilled = () => { }
        } if (typeof onRejected !== 'function') {
            onRejected = () => { }
        }

        //执行resole reject里面异步 只要等待后才能then
        if (this.status === myPromise.PENDING) {
            this.callback.push({
                onFulfilled: value => {
                    try {
                        onFulfilled(value)
                    } catch (error) {
                        onRejected(error)
                    }
                },
                onRejected: value => {
                    try {
                        onRejected(value)
                    } catch (error) {
                        onRejected(error)
                    }
                }
            })
        }
        //在没有resolve和reject之前就不能执行then
        if (this.status === myPromise.FULFILLED) {
            setTimeout(() => {//异步比同步晚执行
                try { //解决then回调后 错误
                    onFulfilled(this.value)
                } catch (error) {
                    onRejected(error)
                }
            })
        }

        if (this.status === myPromise.REJECTED) {
            setTimeout(() => {
                try {
                    onRejected(this.value)
                } catch (error) {
                    onRejected(error)
                }
            })

        }
    }
}